package sqlexplorer.commands;

import java.security.InvalidParameterException;
import java.sql.Connection;
import java.sql.SQLException;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.PlatformUI;

import sqlexplorer.application.ConnectionsController;
import sqlexplorer.application.SqlController;
import sqlexplorer.application.exceptions.NotConnectedException;
import sqlexplorer.ui.views.CreateConnectionDialog;
import sqlexplorer.ui.views.QueryView;

public class ExecuteQueryHandler extends AbstractHandler {

	/**
	 * Execute the query
	 */
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		
		IViewReference [] iviews = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getViewReferences();
		
		for(IViewReference viewReference : iviews) {
			//ConnectionsView connectionView = (ConnectionsView)viewReference.getView(true);
			if(viewReference.getId().equals("sqlexplorer.ui.views.queryview")) {
				QueryView queryView = (QueryView)viewReference.getView(true);
				String query = queryView.getQuery();
				Shell shell = queryView.getSite().getShell();
				Connection connection = ConnectionsController.getInstance().getConnection();
				if(connection != null) {
					if(query != null && !query.isEmpty())
					{
						try {
							SqlController.getInstance().executeSql(query);
						} catch (InvalidParameterException e) {
							MessageBox msgBox=new MessageBox(shell ,SWT.ICON_WARNING|SWT.OK);
							msgBox.setText("Warning");
							msgBox.setMessage("Connection failed.");
							msgBox.open();
						} catch (NotConnectedException e) {
							MessageBox msgBox=new MessageBox(shell ,SWT.ICON_WARNING|SWT.OK);
							msgBox.setText("Warning");
							msgBox.setMessage("Connection failed.");
							msgBox.open();
						} catch (SQLException e) {
							MessageBox msgBox=new MessageBox(shell ,SWT.ICON_WARNING|SWT.OK);
							msgBox.setText("Warning");
							msgBox.setMessage("The statement is not correct.");
							msgBox.open();
						}
					} else {
						MessageBox msgBox=new MessageBox(queryView.getSite().getShell() ,SWT.ICON_WARNING|SWT.OK);
						msgBox.setText("Warning");
						msgBox.setMessage("Please enter a query.");
						
						msgBox.open();
					}
				}else {
					MessageBox msgBox=new MessageBox(queryView.getSite().getShell() ,SWT.ICON_WARNING|SWT.OK);
					msgBox.setText("Warning");
					msgBox.setMessage("Please connect to a database.");
					
					msgBox.open();
				}
			}
			//connectionView.addItem();
		}
		return null;
	}

}
